import CryptoJS from 'crypto-js'

/**
 * 灵芯平台语音客户端
 */
export class LingxinApiClientBase {
  // 企业在灵芯的唯一标识
  lingxinAppId
  // uniapp的deviceId，用作设备的SN号
  appId
  // app的语音License
  appLicenseKey
  // websocket客户端
  socketTask
  // socket是否已经连接
  isConnected = false

  constructor(lingxinAppId, appId, appLicenseKey) {
    this.lingxinAppId = lingxinAppId
    this.appId = appId
    this.appLicenseKey = appLicenseKey
    this.isConnected = false
  }

  /**
   * 生成签名
   */
  generateSignature(timestamp) {
    // 拼接签名字符串
    let signText = `app_id=${this.lingxinAppId}&sn=${this.appId}&timestamp=${timestamp}`
    // 计算 HMAC-SHA1
    const hmac = CryptoJS.HmacSHA1(signText, this.appLicenseKey)
    // 或者转换为 Base64
    const base64Signature = hmac.toString(CryptoJS.enc.Base64)
    // 返回
    return base64Signature
  }

  /**
   * 创建socket链接
   */
  createSocketConnection() {
    return new Promise((resolve, reject) => {
      // 时间戳，毫秒
      const timestamp = Date.now() + ''
      // 构建HTTP头部，包含签名认证信息
      const headers = {
        app_id: this.lingxinAppId,
        sn: this.appId,
        timestamp: timestamp,
        signature: this.generateSignature(timestamp)
      }
      // console.log("header参数：", headers)
      // 创建socket链接
      // let steupSocketSuccess = false
      const socketTask = uni.connectSocket({
        url: 'wss://eagent.edu-aliyun.com/gw/ws/open/api/v1/agentChat',
        header: headers,
        // protocols: ["protocol1"],
        method: 'GET',
        success: result => {
          console.log('WebSocket 创建成功', result)
          resolve(socketTask)
        },
        fail: error => {
          console.error('WebSocket 创建失败:', error)
          reject(error)
        }
      })
      // resolve(socketTask)
    })
  }
  /**
   * 建立socket链接并初始化监听器
   */
  setupSocket() {
    return new Promise((resolve, reject) => {
      this.createSocketConnection()
        .then(task => {
          this.socketTask = task
          this.setupEventListeners(resolve, reject)
        })
        .catch(e => {
          console.log('错误：', e)
          reject(e)
        })
    })
  }
  /**
   * 关闭socket链接
   */
  closeSocket() {
    return new Promise((resolve, reject) => {
      if (this.socketTask) {
        this.socketTask.close({
          code: 1000,
          reason: '正常关闭',
          success: () => {
            resolve(true)
          },
          fail: () => {
            reject('关闭失败')
          },
          complete: () => {}
        })
      }
    })
  }

  /**
   * 发送消息
   * @param {String | ArrayBuffer} data 消息
   */
  send(data) {
    return new Promise((resolve, reject) => {
      if (this.socketTask) {
        this.socketTask.send({
          data: data,
          success: () => {
            resolve(true)
          },
          fail: data => {
            reject('发送消息失败：', data)
          },
          complete: () => {}
        })
      }
    })
  }

  /**
   * 设置事件监听器
   */
  setupEventListeners(resolve, reject) {
    console.log('初始化WebSocket监听器')
    if (!this.socketTask) {
      reject('socketTask初始化失败')
      return
    }

    // 监听连接打开
    this.socketTask.onOpen(res => {
      console.log('WebSocket 连接已打开', res)
      this.isConnected = true
      resolve(res)
    })

    // 监听消息接收
    this.socketTask.onMessage(res => {
      // console.log('收到 WebSocket 消息:', res)
      try {
        this.onMessageRecived(res.data)
      } catch (error) {
        console.error('消息解析错误:', error)
      }
    })

    // 监听连接关闭
    this.socketTask.onClose(res => {
      console.log('WebSocket 连接已关闭', res)
      this.isConnected = false
    })

    // 监听错误
    this.socketTask.onError(error => {
      console.error('WebSocket 错误:', error)
      this.isConnected = false
      reject(error)
    })
  }

  /**
   * 接收到云端的推送信息
   * @param {String | ArrayBuffer} message
   */
  onMessageRecived(message) {
    console.log('灵芯Socket接收到消息：', message)
  }
}
